/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.dao.impl;

import es.silenus.detecta.dao.Page;
import es.silenus.detecta.dao.TrainingActionDAO;

import es.silenus.detecta.model.KnowledgeUnit;
import es.silenus.detecta.model.TrainingAction;

import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Map;


/**
 * DOCUMENT ME!
 *
 * @author <a href="mailto:dgarcia@silenus-consultoria.es">Daniel Garc&iacute;a</a>
 *
 * @since 02-abr-2009 13:09:00
 */
public class TrainingActionDAOImpl extends ReadWriteDAOImpl<TrainingAction, Integer> implements TrainingActionDAO {
	/**
	 * The check remove actions SQL.
	 */
	private String checkRemoveActionsSQL;

	/**
	 * Sets the check remove actions SQL.
	 *
	 * @param checkRemoveActionsSQL the check remove actions SQL.
	 */
	public void setCheckRemoveActionsSQL(String checkRemoveActionsSQL) {
		this.checkRemoveActionsSQL = checkRemoveActionsSQL;
	}

	/**
	 * Finds a training action by its code (unique in an organization)
	 *
	 * @param code the code.
	 * @param organizationId the organizationId.
	 *
	 * @return the training action.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public TrainingAction findByCode(final String code, int organizationId) {
		Session session = null;

		try {
			session = getSession();

			return (TrainingAction)session.getNamedQuery(TrainingAction.class.getName() + ".findByCode")
																		.setString("code", code).setInteger("organizationId", organizationId).uniqueResult();
		} finally {
			releaseSession(session);
		}
	}

	/**
	 * Retrieves the trainings actions a given organization owns.
	 *
	 * @param organizationId the organization id.
	 *
	 * @return the list of trainings actions.
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<TrainingAction> findByOrganization(int organizationId) {
		Session session = null;

		try {
			session = getSession();

			return (List<TrainingAction>)session.getNamedQuery(TrainingAction.class.getName() + ".findByOrganization")
																					.setInteger("organizationId", organizationId)
																					.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY).list();
		} finally {
			releaseSession(session);
		}
	}

	/**
	 * Override this method to provide a find by example page criteria.
	 *
	 * @param criteria the criteria.
	 * @param object the sample object.
	 *
	 * @return the criteria.
	 */
	protected DetachedCriteria preparePageCriteria(final DetachedCriteria criteria, final Map<String, Object> object) {
		criteria.setFetchMode("organization", FetchMode.JOIN);

		Object temp = object.get("id");

		if(temp != null) {
			criteria.add(Restrictions.eq("id", temp));
		}

		temp = object.get("code");

		if(temp != null) {
			criteria.add(Restrictions.ilike("code", (String)temp, MatchMode.ANYWHERE));
		}

		temp = object.get("name");

		if(temp != null) {
			criteria.add(Restrictions.ilike("name", (String)temp, MatchMode.ANYWHERE));
		}

		temp = object.get("description");

		if(temp != null) {
			criteria.add(Restrictions.ilike("description", (String)temp, MatchMode.ANYWHERE));
		}

		temp = object.get("organization.id");

		if(temp != null) {
			criteria.add(Restrictions.eq("organization.id", temp));
		}

		return criteria;
	}

	/**
	 * Override this method to provide a find by example list criteria.
	 *
	 * @param criteria the criteria.
	 * @param object the sample object.
	 *
	 * @return the criteria.
	 */
	protected DetachedCriteria prepareListCriteria(final DetachedCriteria criteria, final Map<String, Object> object) {
		return preparePageCriteria(criteria, object);
	}

	/**
	 * Finds units associated with the given criteria.
	 *
	 * @param sample the sample criteria.
	 * @param start the start index.
	 * @param limit the limit index.
	 * @param sortFields the sort fields.
	 * @param sortDirections the sort directions.
	 *
	 * @return the page.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Page<KnowledgeUnit> findAssociatedUnits(
		final Map<String, Object> sample, int start, int limit, final String[] sortFields, final String[] sortDirections) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName("KnowledgeUnit");

		// Prepare the page criteria
		criteria.add(
			Restrictions.sqlRestriction(
				"EXISTS (SELECT 1 FROM training_actions_units a WHERE a.id_unit={alias}.id_unit AND a.id_action=?)",
				sample.get("id"), Hibernate.INTEGER));


		// Build page and paginate
		PageImpl<KnowledgeUnit> page = new PageImpl<KnowledgeUnit>(getSessionFactory());

		page.setStart(start);
		page.setLimit(limit);
		page.setCriteria(criteria);

		if((sortFields != null) && (sortDirections != null) && (sortFields.length == sortDirections.length)) {
			for(int i = 0; i < sortFields.length; ++i) {
				page.addSort(sortFields[i], sortDirections[i]);
			}
		}

		page.paginate();

		return page;
	}

	/**
	 * Finds units non associated with the given criteria.
	 *
	 * @param sample the sample criteria.
	 * @param start the start index.
	 * @param limit the limit index.
	 * @param sortFields the sort fields.
	 * @param sortDirections the sort directions.
	 *
	 * @return the page.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Page<KnowledgeUnit> findNonAssociatedUnits(
		final Map<String, Object> sample, int start, int limit, final String[] sortFields, final String[] sortDirections) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName("KnowledgeUnit");

		// Prepare the page criteria
		criteria.add(
			Restrictions.sqlRestriction(
				"NOT EXISTS (SELECT 1 FROM training_actions_units a WHERE a.id_unit={alias}.id_unit AND a.id_action=?)",
				sample.get("id"), Hibernate.INTEGER));


		// Build page and paginate
		PageImpl<KnowledgeUnit> page = new PageImpl<KnowledgeUnit>(getSessionFactory());

		page.setStart(start);
		page.setLimit(limit);
		page.setCriteria(criteria);

		if((sortFields != null) && (sortDirections != null) && (sortFields.length == sortDirections.length)) {
			for(int i = 0; i < sortFields.length; ++i) {
				page.addSort(sortFields[i], sortDirections[i]);
			}
		}

		page.paginate();

		return page;
	}

	/**
	 * Retrieves the removal information of entities with the given keys.
	 *
	 * @param keys the keys.
	 *
	 * @return the information requested.
	 */
	@SuppressWarnings({"unchecked"})
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Map<String, Object>> getRemovalInformation(final Integer[] keys) {
		MapSqlParameterSource args = new MapSqlParameterSource();

		args.addValue("ids", asList(keys));

		return jdbcTemplate.queryForList(checkRemoveActionsSQL, args);
	}

	/**
	 * Removes training actions by keys.
	 *
	 * @param keys the keys.
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void remove(final Integer[] keys) {
		List<TrainingAction> elements = findByIds(keys);

		for(TrainingAction element : elements) {
			super.remove(element);
		}
	}
}
